package com.eclipse.training.extensions.ui;

import java.io.IOException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.xml.sax.SAXException;

import com.eclipse.training.extensions.LogManager;
import com.eclipse.training.models.ModelContainer;
import com.eclipse.training.models.ModelProvider;

public class ModelContentProvider implements ITreeContentProvider {

	@Override
	public void dispose() {
	}

	@Override
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
	}

	@Override
	public Object[] getElements(Object inputElement) {
		/*
		 * Avoid recursion bug
		 * 
		 * NOTE: The returned array must not contain the given inputElement,
		 * since this leads to recursion issues in AbstractTreeViewer (see bug
		 * 9262).
		 */

		if (inputElement instanceof ModelContainer) {
			ModelContainer root = new ModelContainer(
					((ModelContainer) inputElement).getName());
			root.setElements(((ModelContainer) inputElement).getElements());
			return new Object[] { root };
		}
		return null;
	}

	@Override
	public Object[] getChildren(Object parentElement) {
		if (parentElement instanceof IFile) {
			// Utils.activateLinkWithEditor();
			try {
				ModelContainer model = ModelProvider
						.update((IFile) parentElement);
				return new Object[] { model };
			} catch (CoreException | SAXException | IOException e) {
				LogManager.getLogger().logError(e);
				return null;
			}
		} else if (parentElement instanceof ModelContainer)
			return ((ModelContainer) parentElement).getElements().toArray();

		return null;
	}

	@Override
	public Object getParent(Object element) {
		return null;
	}

	@Override
	public boolean hasChildren(Object element) {
		if (element instanceof ModelContainer)
			return ((ModelContainer) element).getElements().size() > 0;
		return false;
	}

}
